<?php
	$db = new mysqli("127.0.0.1","fc","keks");
	if(mysqli_connect_errno($db))
	{
		die("failed to Connect to Database: ". mysqli_connect_error());
	}
	updateusernames($db);
	
	function updateusernames($db)
	{
		echo "updating usernames";
		$sql="SELECT id,wotaccountid,wotaccountname FROM wottools.users;";
		$stmt = $db->prepare($sql);
		if(!$stmt)
		{
			return $db->error;
		}
		if(!$stmt->execute())
		{
			return $stmt->error;
		}
		
		$stmt->bind_result($id,$wotaccountid,$wotaccountname);
		$stmt->store_result();
		while($stmt->fetch())
		{
			if($wotaccountid>0&&$wotaccountname==="default accountname"||$wotaccountid>0&&$wotaccountname==="0")
			{
				//echo "USERNAME=".getusername($wotaccountid)."<br>";
				updateusername($db,$id,getusername($wotaccountid));
			}
		}
		$stmt->free_result();
		$stmt->close();
	}
	
	
	function updateusername($db,$id, $name)
	{
	echo "updating user".$id."<br>";
		$sql= "UPDATE wottools.users SET wotaccountname=? WHERE id=?;";
		//echo $sql."<p> id=".$id." name=".$name."\r\n";
		$stmt = $db->prepare($sql);
		if(!$stmt)
		{
			echo "cant prep updateusername";
			echo $db->error;
			return $db->error;
		}
		$stmt->bind_param("si",$name,$id);
		if(!$stmt->execute())
		{
			echo "cant ex updateusername";
			return $stmt->error;
		}
		$stmt->close();
	}
	
	function getusername($wotid)
	{
		$handle = fopen("http://worldoftanks.eu/community/accounts/".$wotid."/","r");
		$buffer = '';
		if ($handle) {
			while (!feof($handle)) {
				$buffer .= fgetss($handle, 5000);
			}
		}
		fclose($handle);
		
		//echo $buffer;
		$pos1 = strpos($buffer, 'Player Profile ');
		$pos2 = strpos($buffer, '|');
		echo $pos1.".".$pos2."<br>";
		$resultingString = substr($buffer, $pos1+15, $pos2-$pos1-15);
		
		return $resultingString;
	}
	
?>